<template>
  <div>
    <el-button type="primary"
               @click="addImage">添加图片</el-button>

    <el-table ref="bannerTable"
              :data="bannerList"
              style="width: 100%"
              row-key="id">
      <el-table-column :prop="index"
                       :label="item"
                       v-for="(item, index) in tableColumList"
                       :key="index">
        <template slot-scope="scope">
          <!-- <el-image
          :prop="index.bannerUrl"
          :src="scope.row.bannerUrl"
        />
        <div v-else >{{ scope.row[index] }}</div> -->
          <div v-if="item == `图片`">
            <el-image :prop="index.bannerUrl"
                      :src="scope.row.bannerUrl"
                      no-cache="true"
                      style="width: 120 ; height:90px ;  ">
              <div slot="error"
                   class="image-slot">
                <i> 暂无图片</i>
              </div>
            </el-image>
          </div>
          <div v-else-if="item == `状态`">
            <el-tag v-if="scope.row.status == 1"
                    size="medium"> 有效</el-tag>
            <el-tag v-else
                    size="danger">无效</el-tag>
          </div>
          <div v-else-if="item == `跳转分类`">
            {{ scope.row.categoryBean.name }}
          </div>
          <div v-else-if="item == `操作`"
               style="display: inline-block">
            <el-button type="primary"
                       icon="el-icon-edit"
                       circle
                       @click="editBanner(scope.row)"></el-button>
            <el-button type="danger"
                       icon="el-icon-delete"
                       circle
                       @click="deleteBanner(scope.row)"></el-button>
          </div>
          <div v-else>{{ scope.row[index] }}</div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="handleSizeChange"
                   @current-change="handleCurrentChange"
                   layout="total ,sizes, prev, pager, next"
                   :page-sizes="[2, 4]"
                   :currnt-page="this.currentPageNum"
                   :page-size="this.currentPageSize"
                   :total="this.totalNum">
    </el-pagination>

    <el-dialog title="添加图片"
               :visible.sync="dialogVisible">
      <el-form ref="form"
               :model="form"
               :rules="rules"
               label-width="80px">
        <el-form-item label="图片名称"
                      prop="imgName">
          <el-input v-model="form.imgName"></el-input>
        </el-form-item>
        <el-form-item label="排序值"
                      prop="sort">
          <el-input v-model="form.sort"> </el-input>
        </el-form-item>
        <el-form-item label="指向分类"
                      prop="categoryId">
          <el-select v-model="form.categoryId"
                     placeholder="请选择指向分类">
            <el-option v-for="item in categorySelectList"
                       :key="item.index"
                       :value="item.id"
                       :label="item.name"></el-option>

          </el-select>
        </el-form-item>

        <el-form-item label="添加图片">
          <el-upload ref="upload"
                     action
                     :accept="'.jpg'"
                     :http-request="uploadImage"
                     list-type="picture-card"
                     :limit="1"
                     :show-file-list="true"
                     :auto-upload="false"
                     :on-change="change"
                     :on-exceed="exceed">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>

        <el-form-item>
          <el-button type="primary"
                     @click="onSubmit('form')">提交</el-button>
          <el-button type="primary"
                     @click="closeDialog('form')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 修改轮播图弹窗-->
    <el-dialog title="编辑轮播图"
               :visible.sync="editBannerDialogVisible">
      <el-form :model="editForm"
               ref="editForm"
               :rules="rules"
               label-width="80px">

        <el-form-item label="编号">
          <el-input v-model="editForm.id"
                    :disabled="true"></el-input>
        </el-form-item>

        <el-form-item label="图片名称"
                      prop="imgName">
          <el-input v-model="editForm.imgName"></el-input>
        </el-form-item>

        <el-form-item label="指向分类"
                      prop="categoryId">
          <el-select v-model="editForm.categoryId"
                     placeholder="请选择指向分类">
            <el-option v-for="item in categorySelectList"
                       :key="item.index"
                       :value="item.id"
                       :label="item.name"></el-option>

          </el-select>
        </el-form-item>

        <el-form-item label="排序值"
                      prop="sort">
          <el-input v-model="editForm.sort"></el-input>
        </el-form-item>
        <el-form-item label="修改图片">
          <el-upload ref="upload"
                     action
                     :accept="'.jpg'"
                     :http-request="editImage"
                     list-type="picture-card"
                     :limit="1"
                     :show-file-list="true"
                     :auto-upload="false"
                     :file-list="editFileList"
                     :on-change="editChange"
                     :on-exceed="exceed">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-button type="primary"
                   @click="onSubmitEdit('editForm')">提交</el-button>
        <el-button type="primary"
                   @click="closeEditDialog('editForm')">取消</el-button>

      </el-form>

    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "BannerSetting",
  components: {},
  data() {
    return {
      bannerList: [],
      tableColumList: {
        id: "编号",
        imgName: "图片名称",
        bannerUrl: "图片",
        sort: "排序值",
        status: "状态",
        categoryId: "跳转分类",
        createTime: "创建时间",
        updateTime: "更新时间",
        tool: "操作",
      },
      isChangeImage: false,
      //添加轮播图弹窗
      dialogVisible: false,
      editBannerDialogVisible: false,
      form: {
        imgName: '',
        sort: 0,
        categoryId: '',
      },
      editForm: {
        id: "",
        imgName: "",
        sort: 0,
        imgUrl: "",
        categoryId: '',
      },
      //添加轮播图
      fileArry: [],
      // 修改轮播图
      editFileArray: [],
      headers: {
        "Content-Type": "multipart/form-data",
      },
      // 上传和编辑 使用同一个rules规则校验
      rules: {
        imgName: [{ required: true, message: "图片名称不能为空", trigger: "blur" }],
        sort: [{ required: true, message: "排序值不能为空", trigger: "blur" }],
        categoryId: [{ required: true, message: "请选择分类", trigger: "blur" }],
      },
      editFileList: [],
      // 分页数据
      currentPageNum: 1, // 当前页的页码
      currentPageSize: 2, //当前页显示多少条
      totalNum: 0, // 总数多少条
      categorySelectList: [],
    };
  },
  created() { },
  methods: {
    initBannerData(currentPageNum, currentPageSize) {
      this.getRequest("/banner/api/list", {
        pageNum: currentPageNum,
        pageSize: currentPageSize,
      }).then((res) => {
        console.log(res);
        if (res.code == 200 && res.msg == "success") {
          this.bannerList = res.data;
          this.totalNum = res.total;
        } else {
          this.$alert("错误了", "提示", {
            confirmButtonText: "确定",
          });
        }
      });
    },
    addImage() {
      this.dialogVisible = true;
    },
    onSubmit(formName) {
      let params = new FormData();
      params.append("imgName", this.form.imgName);
      params.append("sort", this.form.sort);
      params.append("categoryId", this.form.categoryId);
      params.append("file", this.fileArry[0]);
      // console.log(params);

      this.$refs[formName].validate((valid) => {
        // 校验表单不能为空
        if (valid) {
          this.uploadRequest(
            "/banner/api/uploadImg",
            params,
            this.headers
          ).then((res) => {
            console.log(res);
            if (res.code == 200) {
              this.$message({
                message: "添加成功",
                type: "success",
              });
              // 关闭弹窗
              this.closeDialog("form");
              //刷新表格
              this.refreshTable();
            } else {
              this.$message.error(res.msg);
            }
          });
        } else {
          this.$message.error(valid.err[0].message);
        }
      });
    },
    // 修改提交
    onSubmitEdit(formName) {
      // 构造参数
      let params = new FormData();
      params.append("id", this.editForm.id);
      params.append("imgName", this.editForm.imgName);
      params.append("sort", this.editForm.sort);
      params.append("categoryId", this.editForm.categoryId);
      if (this.isChangeImage) {
        params.append("isChangeImage", this.isChangeImage);
      }
      //  params.append("file", this.editFileArray[0]);
      params.append("isChangeImage", this.isChangeImage);
      // 校验 表单不能为空
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.uploadRequest("/banner/api/update", params, this.headers).then(
            (res) => {
              console.log(res);
              if (res.code == 200 && res.msg == "success") {
                this.$message({
                  message: "修改成功",
                  type: "success",
                });
                this.closeEditDialog("editForm");
                this.isChangeImage = false;
                this.refreshTable();
              } else {
                // this.$message.error(res.msg);
                 this.$confirm(res.msg, "提示", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  showCancelButton: true,
                  type: "warning",
              })
            }}
          );
        } else {
          this.$message.error(valid.err[0].message);
        }
      });
    },

    // 取消点击 关闭弹窗 弹窗一关闭就清空表单
    closeDialog(formName) {
      this.dialogVisible = false;
      this.$refs[formName].resetFields();
      this.$refs.upload.clearFiles();
      this.fileArry = [];

    },

    closeEditDialog(formName) {
      this.editBannerDialogVisible = false;
      // this.editFileArray = [];
    },

    change(file, fileList) {
      //  console.log(file  )
      //  console.log(fileList)

      if (fileList.length > 0) {
        //console.log([fileList[fileList.length - 1]]);
        // this.fileArry = [fileList[fileList.length - 1]];
        // console.log(file);
        this.fileArry.push(file.raw);
      }
    },

    editChange(file, fileList) {
      this.isChangeImage = true;
      if (fileList.length > 0) {
        this.editFileArray.push(file.raw);
      }
    },
    // 上传和编辑使用同一个exceed方法限制上传一张图片
    exceed() {
      this.$message.warning(`当前限制选择 1个文件`);
    },

    uploadImage(option) {
      this.fileArry.push(option);
    },

    editImage(option) {
      this.editFileArray.push(option);
    },


    // 当前页变化
    handleCurrentChange(val) {
      this.currentPageNum = val;
      this.initBannerData(this.currentPageNum, this.currentPageSize);
    },
    //当前页条数变化
    handleSizeChange(val) {
      this.currentPageSize = val;
      this.initBannerData(this.currentPageNum, this.currentPageSize);
    },

    //刷新表格
    refreshTable() {
      this.initBannerData(this.currentPageNum, this.currentPageSize);
    },
    editBanner(row) {
      this.getRequest("/banner/api/getBannerById/" + row.id).then((res) => {
        console.log(res.data);
        if (res.code == 200 && res.msg == "success") {
          this.editForm = res.data;
          //回显图片
          this.editFileList = [{ name: res.data.imgName, url: res.data.bannerUrl }];

          this.editBannerDialogVisible = true;
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    deleteBanner(row) {
      // console.log(row.id)
      this.$confirm("此操作将永久删除该文件，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        showCancelButton: true,
        type: "warning",
      }).then(() => {
        this.deleteRequest("/banner/api/delete/" + row.id).then((res) => {
          console.log(res);
          if (res.msg == "success" && res.code == 200) {
            this.$message({
              type: "success",
              message: "删除成功",
            });
            this.refreshTable();
          } else {
            this.$message.error(res.msg);
          }
        });
      })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    getCategorySelectList() {
      this.getRequest("/category/api/getAllFirstCategory").then((res) => {
        console.log(res);
        if (res.code == 200 && res.msg == "success") {
          this.categorySelectList = res.data;
        } else {
          this.$message.error(res.msg);
        }
      });
    },
  },

  mounted() {
    this.initBannerData(this.currentPageNum, this.currentPageSize);
    this.getCategorySelectList();
  },
};
</script>

<style scoped></style>
